﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Newtonsoft.Json;

namespace Infrastructure.WebApi
{
    /// <summary>
    /// 请求频率限制Middleware；基于clientId(Connection.Id)
    /// </summary>
    public class RequestLimitMiddleware
    {
        private readonly RequestDelegate _next;
        public RequestLimitMiddleware(RequestDelegate requestDelegate)
        {
            _next = requestDelegate;
        }
        public async Task Invoke(HttpContext httpContext)
        {
            var endPoint = httpContext.Features.Get<IEndpointFeature>()?.Endpoint;
            if (endPoint != null && endPoint.Metadata.GetMetadata<RequestLimitAttribute>() != null)
            {
                var key = $"RequestLimit:{httpContext.Connection.Id}:{httpContext.Request.Path}";
                if (await RedisHelper.SetNxAsync(key, true))
                {
                    await RedisHelper.ExpireAsync(key, 2);
                }
                else
                {
                    var result = new ResponseBase("操作过于频繁", ApiCode.RequestError);
                    httpContext.Response.ContentType = "application/json;charset=utf-8";
                    await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(result));
                    return;
                }
            }
            await _next(httpContext);
        }
    }
    /// <summary>
    /// 请求频率限制Attribute
    /// </summary>
    public class RequestLimitAttribute : Attribute
    {

    }
}
